#ifndef _CRT_MINIHEAP_H_
#define _CRT_MINIHEAP_H_

#ifdef __cplusplus
extern "C" {
#endif

// libuv
typedef struct heap_node _heap_node_t;
typedef struct heap _heap_t;

struct heap_node {
    struct heap_node* left;
    struct heap_node* right;
    struct heap_node* parent;
};

/* A binary min heap.  The usual properties hold: the root is the lowest
 * element in the set, the height of the tree is at most log2(nodes) and
 * it's always a complete binary tree.
 *
 * The heap function try hard to detect corrupted tree nodes at the cost
 * of a minor reduction in performance.  Compile with -DNDEBUG to disable.
 */
struct heap {
    struct heap_node* root;
    unsigned int count;
};

/* Return non-zero if a < b. */
typedef int (*heap_compare_fn)(const struct heap_node* a, const struct heap_node* b);
/* Implementation follows. */
void heap_init(_heap_t* heap);
_heap_node_t* heap_root(const _heap_t* heap);
void heap_insert(_heap_t* heap, struct heap_node* newnode, heap_compare_fn less_than);
void heap_remove(_heap_t* heap, struct heap_node* node, heap_compare_fn less_than);
void heap_dequeue(_heap_t* heap, heap_compare_fn less_than);

#ifdef __cplusplus
}
#endif

#endif
